import React, { Component } from 'react';
import { connect } from 'dva';
import { message, Modal, Button } from 'antd';
import styles from './../Users.css';
import moment from 'moment';
import Factory from '../../factory';
import * as datetime from '../../../utils/datetime'
import dataEditCreate from '../../addons/DataEdit'
import dataTableCreate from '../../addons/DataTable'
import { deepEqual } from '../../../utils/objects';
import * as common from '../../../utils/common';
const daoName = "BASE_LDJS_XM";
const ButtonGroup = Button.Group;
const columns = [
  { title: '竞赛内容', dataIndex: 'JSNR', key: 'JSNR', width: 300, sorter: true, dispaly: true, filter: true, export: true },
  { title: '竞赛产品', dataIndex: 'JSCP', key: 'JSCP', width: 130, sorter: true, dispaly: true, filter: true, export: true },
  { title: '竞赛目标(万)', width: 150, sorter: false, className: "column-money", caption: 'JSMB', render: data => common.formatNumber(data.JSMB), key: 'JSMB', dispaly: true, filter: false, export: true },
  { title: '竞赛起始日', width: 150, sorter: true, key: 'JSQSR', caption: "JSQSR", render: data => datetime.format(data.JSQSR, "yyyy-MM-dd"), dispaly: true, filter: true, export: true },
  { title: '竞赛截止日', width: 150, sorter: true, key: 'JSJZR', caption: "JSJZR", render: data => datetime.format(data.JSJZR, "yyyy-MM-dd"), dispaly: true, filter: true, export: true },
  { title: '竞赛范围', dataIndex: 'JSFW', key: 'JSFW', width: 150, sorter: true, dispaly: true, filter: true, export: true },
  { title: '奖励标准', dataIndex: 'JLBZ', key: 'JLBZ', width: 250, sorter: true, dispaly: true, filter: true, export: true },
  { title: '资源类型', dataIndex: 'ZYLX', key: 'ZYLX', width: 150, sorter: true, dispaly: true, filter: true, export: true },
  { title: '竞赛预算(万)', width: 150, sorter: false, className: "column-money", caption: 'JSYS', render: data => common.formatNumber(data.JSYS), key: 'JSYS', dispaly: true, filter: false, export: true },
];
let controls = [
  { name: 'JSNR', required: true, type: 'textarea', label: '竞赛内容', dataType: "string", grid: 24 / 24 },
  { name: 'JSCP', required: true, type: 'text', label: '竞赛产品', dataType: "string", grid: 24 / 24 },
  { name: 'JSMB', required: true, type: 'number', label: '竞赛目标(万)', dataType: "number", grid: 24 / 24 },
  { name: 'JSQSR', required: true, type: 'date', label: '竞赛起始日', dataType: "date", grid: 12 / 24, layout: { labelSpan: 10, wrapperSpan: 13 } },
  { name: 'JSJZR', required: true, type: 'date', label: '竞赛截止日', dataType: "date", grid: 12 / 24, layout: { labelSpan: 10, wrapperSpan: 13 } },
  {
    name: "JSFW", label: "竞赛范围", required: true,
    data: [
      { value: '全行（含二级分行）', label: '全行（含二级分行）' },
      { value: '南京分行（不含二级分行）', label: '南京分行（不含二级分行）' },
      { value: '其他', label: '其他' },
    ],
    grid: 24 / 24, type: "select", onChange: (t) => {
      // 获取当前选择值
      if (t == "其他") {
        controls.map((v, i) => {
          if (v.name == "JSFW") {
            controls[i + 1].type = 'text';
            controls[i + 1].placeholder = '请在此处填入竞赛范围详细的说明';
            controls[i + 1].required = true
          }
        })
      } else {
        controls.map((v, i) => {
          if (v.name == "JSFW") {
            controls[i + 1].type = 'disabled';
            controls[i + 1].placeholder = '当竞赛范围为选择【其他】时，此处需要填入详细的说明';
            controls[i + 1].required = false
          }
        })
      }
    }
  },
  { name: 'JSFWQT', type: 'disabled', label: '竞赛范围(其他)', dataType: "string", grid: 24 / 24, placeholder: "当竞赛范围为选择【其他】时，此处需要填入详细的说明" },
  { name: 'JLBZ', required: true, type: 'textarea', label: '奖励标准', dataType: "string", grid: 24 / 24 },
  {
    name: "ZYLX", label: "资源类型", required: true,
    data: [
      { value: '绩效资源', label: '绩效资源' },
      { value: '费用额度', label: '费用额度' },
      { value: '其他', label: '其他' },
    ],
    grid: 24 / 24, type: "select", onChange: (t) => {
      // 获取当前选择值
      if (t == "其他") {
        controls.map((v, i) => {
          if (v.name == "ZYLX") {
            controls[i + 1].type = 'text';
            controls[i + 1].placeholder = '请在此处填入资源类型详细的说明';
            controls[i + 1].required = true
          }
        })
      } else {
        controls.map((v, i) => {
          if (v.name == "ZYLX") {
            controls[i + 1].type = 'disabled';
            controls[i + 1].placeholder = '当资源类型为选择【其他】时，此处需要填入详细的说明';
            controls[i + 1].required = false
          }
        })
      }
    }
  },
  { name: 'ZYLXQT', required: false, type: 'disabled', label: '资源类型(其他)', dataType: "string", grid: 24 / 24, placeholder: "当资源类型为选择【其他】时，此处需要填入详细的说明" },
  { name: 'JSYS', required: true, type: 'number', label: '竞赛预算(万)', dataType: "number", grid: 24 / 24 },
];
const EditFrom = dataEditCreate(daoName);
const DataTable = dataTableCreate(daoName);
class LDJSSQ_XMForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataChange: false,
      rwid: 0,
      isShowBtn: true
    };
  }
  componentWillReceiveProps(nextProps) {
    if ((!deepEqual(nextProps.rwid, this.props.rwid)) || (!deepEqual(nextProps.isShowBtn, this.props.isShowBtn))) {
      this.loadData(nextProps.rwid)
      this.state.rwid = nextProps.rwid
      this.state.isShowBtn = nextProps.isShowBtn
    }
  }
  componentDidMount() {
    this.loadData(this.props.rwid)
  }
  loadData(rwid) {
    let seeks = [];
    let whereItems = [];
    whereItems.push({
      FieldName: "JSID",
      Operator: "=",
      FieldValues: '' + rwid
    })
    seeks.push({
      WhereItems: whereItems,
      RelationSign: "AND"
    })
    this.props.dispatch({
      type: `${daoName}/fetch`,
      payload: { daoName, page: 1, pageSize: 20, seeks }
    });
  }
  showModelHandler(isAdd) {
    let key = null
    if (!isAdd) {
      const len = this.props.selectedRowKeys.length;
      if (len === 0) {
        message.info('请选择要编辑的行，如果选择了多行，则使用最后一次选择！');
        return;
      }
      key = this.props.selectedRowKeys[len - 1]
    }
    this.props.dispatch({
      type: `${daoName}/openEdit`,
      payload: { key }
    });
  }
  deleteHandler() {
    const keys = this.props.selectedRowKeys;
    const len = keys.length;
    if (len === 0) {
      message.info('请选择要删除的行！');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: `你确认要删除选中的${len}行数据吗？`,
      okText: '删除',
      cancelText: '取消',
      onOk: () => {
        this.props.dispatch({
          type: `${daoName}/remove`,
          payload: { daoName, keys },
        });
      }
    });
    this.props.dispatch({
      type: `${daoName}/reload`,
      payload: { daoName },
    });
  }
  edidOkHandler() {
    const form = this.refs.LDJSSQ_XMForm.getForm()
    form.validateFields((err, values) => {
      if (!err) {
        let t = `${daoName}/create`
        const { keyName, record } = this.props;
        let msg = "数据添加成功！"
        if (record[keyName]) {
          values[keyName] = record[keyName];
          t = `${daoName}/patch`
          msg = "数据修改成功！"
        }
        controls.map((c, i) => {
          if (c.type === 'cascader-select') {
            let vs = values[c.name];
            if (vs.length > 0) {
              values[c.name] = vs[vs.length - 1];
            } else {
              values[c.name] = null;
            }
          }
          if (c.dataType === "number") {
            values[c.name] = Number(values[c.name])
          } else if (c.dataType === "date" || c.dataType === "datetime") {
            values[c.name] = !values[c.name] ? null : new Date(values[c.name])
          } else {
            values[c.name] = values[c.name] === undefined ? null : values[c.name]
          }
          if (c.multiple || c.type === 'checkbox-group') {
            values[c.name] = values[c.name].join(',');
          }
        })
        this.state.dataChange = true;
        values.JSID = this.state.rwid
        this.props.dispatch({
          type: t,
          payload: { daoName, values },
        })
      }
    });
  };
  hideEditHandler() {
    const form = this.refs.LDJSSQ_XMForm.getForm();
    form.resetFields();
    if (this.state.dataChange) {
      this.props.dispatch({
        type: `${daoName}/reload`,
        payload: { daoName },
      });
      this.state.dataChange = false;
    }
    this.props.dispatch({
      type: `${daoName}/hideEdit`
    });
  };
  render() {
    let { showEdit, record, permID, popedomTypes, list } = this.props
    const pTypes = popedomTypes[permID]
    let data = null
    if (this.state.isShowBtn) {
      data = <ButtonGroup style={{ zIndex: 0 }}>
        <Button onClick={this.showModelHandler.bind(this, true)}>新增</Button>
        <Button onClick={this.showModelHandler.bind(this, false)}>修改</Button>
        <Button onClick={this.deleteHandler.bind(this)}>删除</Button>
      </ButtonGroup>
    }
    const zhcbl = list.length === 0 ? 0 : list[0].ZHCBL

    return (
      <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
        <div>
          <div className={styles.create}>
            {data}
          </div>
          <Modal title={"新增项目"} width={700} visible={showEdit} onOk={this.edidOkHandler.bind(this)} onCancel={this.hideEditHandler.bind(this)}
            footer={[
              <Button key="close" type="ghost" onClick={this.hideEditHandler.bind(this)}>关闭</Button>,
              <Button key="submit" type="primary" onClick={this.edidOkHandler.bind(this)}>保存</Button>
            ]}
          >

            <EditFrom ref="LDJSSQ_XMForm" daoName={daoName} controls={controls} record={record} />
          </Modal>
          <DataTable ref="RoleTable" daoName={daoName} columns={columns} controls={controls} permID={permID} />
        </div>
      </div >
    )
  }
}
function mapStateToProps(state) {
  const { showEdit, record, selectedRowKeys, keyName, list } = state[daoName];
  const { userID, orgID, pOrgID, popedomTypes } = state.menus;
  return {
    userID,
    orgID,
    pOrgID,
    popedomTypes,
    showEdit,
    selectedRowKeys,
    keyName,
    record, list
  }
}
LDJSSQ_XMForm = connect(mapStateToProps)(LDJSSQ_XMForm)
export default LDJSSQ_XMForm;

let render = (props) => React.createElement(LDJSSQ_XMForm, props);
let f = new Factory()
f.set("LDJSSQ_XMForm", render)
